package com.github.maojx0630.onebot.socket;

import com.github.maojx0630.onebot.ws.QqBotMessageHandle;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author 毛家兴
 * @since 2024-04-02 09:17
 */
public class OneBotWebSocketHandler extends TextWebSocketHandler {


  private String qq = "";

  private final QqBotMessageHandle qqBotMessageHandle;

  public OneBotWebSocketHandler(QqBotMessageHandle qqBotMessageHandle) {
    this.qqBotMessageHandle = qqBotMessageHandle;
  }

  @Override
  public void afterConnectionEstablished(WebSocketSession session) {
    qq = session.getAttributes().get("qq").toString();
    OneBotUtil.put(qq, session);
  }

  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    qqBotMessageHandle.handle(session, qq, message.getPayload());
  }

  @Override
  public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
    OneBotUtil.remove(qq);
  }
}
